package com.web.logindemo.controller;



import com.web.logindemo.common.HttpStatus;
import com.web.logindemo.common.util.DateUtils;
import com.web.logindemo.common.util.StringUtils;
import com.web.logindemo.common.util.sql.SqlUtils;
import com.web.logindemo.domain.page.PageDomain;
import com.web.logindemo.domain.page.TableDataInfo;
import com.web.logindemo.domain.page.TableSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;

/**
 * web层通用数据处理
 */
public class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 前台传递过来的日期格式的字符串，自动转换为Date类型
     */
    public void initBinder(WebDataBinder binder){
        // Date类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
            @Override
            public void setAsText(String text){
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置分页请求数据
     */
    protected void startPage(){
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if(StringUtils.isNotNull(pageNum)&&StringUtils.isNotNull(pageSize)){
            String orderBy = SqlUtils.escapeOrderBySql(pageDomain.getOrderBy());
            Boolean reasonable = pageDomain.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
    }

    /**
     * 响应请求分页数据
     */
    protected TableDataInfo getDataTable(List<?> list){
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}
